#!/usr/bin/env node

const fs = require('fs')
const path = require('path')

// 图片优化配置
const IMAGE_OPTIMIZATION = {
    // 支持的图片格式
    supportedFormats: ['.png', '.jpg', '.jpeg', '.gif', '.svg', '.webp'],

    // 最大文件大小 (bytes)
    maxFileSize: 500 * 1024, // 500KB

    // 建议的图片尺寸
    recommendedSizes: {
        small: { width: 200, height: 200 },
        medium: { width: 400, height: 400 },
        large: { width: 800, height: 800 }
    }
}

function optimizeImages() {
    console.log('🖼️  图片优化分析')
    console.log('================')

    const srcPath = path.join(__dirname, '../src')
    const publicPath = path.join(__dirname, '../public')

    const imageFiles = []

    // 扫描src目录
    scanDirectory(srcPath, imageFiles)

    // 扫描public目录
    scanDirectory(publicPath, imageFiles)

    if (imageFiles.length === 0) {
        console.log('✅ 未发现图片文件')
        return
    }

    console.log(`📊 发现 ${imageFiles.length} 个图片文件`)
    console.log('')

    // 分析图片
    const analysis = analyzeImages(imageFiles)

    console.log('📈 图片分析结果:')
    console.log(`  总大小: ${formatBytes(analysis.totalSize)}`)
    console.log(`  平均大小: ${formatBytes(analysis.averageSize)}`)
    console.log(`  最大文件: ${analysis.largestFile.name} (${formatBytes(analysis.largestFile.size)})`)
    console.log('')

    // 优化建议
    console.log('💡 优化建议:')

    const oversizedImages = imageFiles.filter(img => img.size > IMAGE_OPTIMIZATION.maxFileSize)
    if (oversizedImages.length > 0) {
        console.log(`  ⚠️  ${oversizedImages.length} 个图片文件过大:`)
        oversizedImages.forEach(img => {
            console.log(`    - ${img.name}: ${formatBytes(img.size)}`)
        })
        console.log('  💡 建议: 压缩这些图片或转换为WebP格式')
    }

    const pngImages = imageFiles.filter(img => img.name.toLowerCase().endsWith('.png'))
    if (pngImages.length > 0) {
        console.log(`  💡 发现 ${pngImages.length} 个PNG文件，建议转换为WebP格式`)
    }

    const jpgImages = imageFiles.filter(img =>
        img.name.toLowerCase().endsWith('.jpg') || img.name.toLowerCase().endsWith('.jpeg')
    )
    if (jpgImages.length > 0) {
        console.log(`  💡 发现 ${jpgImages.length} 个JPG文件，建议压缩或转换为WebP格式`)
    }

    console.log('  ✅ 建议使用图片懒加载')
    console.log('  ✅ 建议使用响应式图片')
    console.log('  ✅ 建议启用图片压缩')
}

function scanDirectory(dir, files) {
    if (!fs.existsSync(dir)) return

    const items = fs.readdirSync(dir)

    for (const item of items) {
        const fullPath = path.join(dir, item)
        const stat = fs.statSync(fullPath)

        if (stat.isDirectory()) {
            scanDirectory(fullPath, files)
        } else {
            const ext = path.extname(item).toLowerCase()
            if (IMAGE_OPTIMIZATION.supportedFormats.includes(ext)) {
                files.push({
                    name: path.relative(process.cwd(), fullPath),
                    size: stat.size,
                    path: fullPath,
                    extension: ext
                })
            }
        }
    }
}

function analyzeImages(images) {
    const totalSize = images.reduce((sum, img) => sum + img.size, 0)
    const averageSize = totalSize / images.length
    const largestFile = images.reduce((largest, img) =>
        img.size > largest.size ? img : largest
    )

    return {
        totalSize,
        averageSize,
        largestFile
    }
}

function formatBytes(bytes) {
    if (bytes === 0) return '0 Bytes'

    const k = 1024
    const sizes = ['Bytes', 'KB', 'MB', 'GB']
    const i = Math.floor(Math.log(bytes) / Math.log(k))

    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

optimizeImages()
